﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Text;
using UnityEngine.Networking;


public delegate void OnHttpError(ServerError error);
public class GameHttpClient
{

    public delegate void HttpJsonResponse(string data);
    private string url;

    public GameHttpClient(String url)
    {
        this.url = url;
    }

    private string ModifyPath(string path)
    {
        if (!path.StartsWith("/", StringComparison.Ordinal))
        {
            path = "/" + path;
        }
        if (path.EndsWith("/", StringComparison.Ordinal))
        {
            path = path.Substring(0, path.Length - 1);
        }
        return path;
    }

    public IEnumerator SendHttpGet(string path, Dictionary<string, string> requestParams, HttpJsonResponse response, OnHttpError httpError)
    {
        path = this.ModifyPath(path);
        if (requestParams != null && requestParams.Count > 0)
        {
            string queryParam = "";
            foreach (KeyValuePair<string, string> param in requestParams)
            {
                queryParam += param.Key + "=" + param.Value + "&";
            }
            queryParam = queryParam.Remove(queryParam.Length - 1);
            url += path + "?" + queryParam;
            Debug.Log("发送Http Get请求：" + url);
        }
        UnityWebRequest httpClient = UnityWebRequest.Get(url);
        
        
        {
            yield return httpClient.SendWebRequest();
            if (httpClient.error != null)
            {
                Debug.LogError("发送Http Get报错：" + httpClient.error);
                ServerError serverError = new ServerError(ServerError.HttpError, httpClient.error);
                httpError(serverError);
            }
            else
            {
                string result = httpClient.downloadHandler.text;
                Debug.Log("收到Get请求响应：" + result);
                response(result);
            }

        }
    }
    public IEnumerator SendHttpPost(string path, object param, HttpJsonResponse response, OnHttpError error)
    {
        return SendHttpPost(path, param, null, response, error);
    }

    public IEnumerator SendHttpPost(string path, object param, Dictionary<string, string> header, HttpJsonResponse response, OnHttpError error)
    {
        path = this.ModifyPath(path);
        byte[] body = null;
        string jsonParam = null;
        if (param != null)
        {
            jsonParam =  JsonConvert.SerializeObject(param);
            body = Encoding.UTF8.GetBytes(jsonParam);
        }
        string target = url + path;
        UnityWebRequest unityWeb = new UnityWebRequest(target, "POST");
        unityWeb.timeout = GameClientConfig.HttpRequestTimeout; //设置超时时间20秒
        if(body != null)
        {
            unityWeb.uploadHandler = new UploadHandlerRaw(body);
        }
        unityWeb.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
        if (header != null)
        {
            foreach (KeyValuePair<string, string> key in header)
            {
                unityWeb.SetRequestHeader(key.Key, key.Value);
            }
        }
        unityWeb.downloadHandler = new DownloadHandlerBuffer();

        Debug.Log("发送 Http Post ：" + target + "\n" + "发送数据：" + jsonParam);
        yield return unityWeb.SendWebRequest();

        if (unityWeb.isDone)
        {
            if (unityWeb.isHttpError || unityWeb.isNetworkError)
            {

                ServerError serverError = new ServerError((int)unityWeb.responseCode, "连接服务器失败，请检测网络");
                Debug.Log("Http Request Error : " + target + ",HttpCode:" + unityWeb.responseCode + ", errorMessage:" + unityWeb.error);
                error(serverError);
            }
            else
            {
                string result = unityWeb.downloadHandler.text;
                Debug.Log("收到Http Post 响应：" + target + " Message : " + result);
                response(result);
            }

        }
        else
        {
            Debug.Log("Http 请求失败: " + target + ",请求参数：" + jsonParam);
            Debug.Log("错误信息：" + unityWeb.error);
            ServerError serverError = new ServerError(ServerError.HttpError, unityWeb.error);
            error(serverError);
        }

    }
}
